<script>
import ItemList from "./components/ItemList.vue";
import ItemSummaryPriceView from "./views/ItemSummaryPriceView.vue";
import BomPriceView from "./views/BomPriceView.vue";
import ItemPriceComparisonView from "./views/ItemPriceComparisonView.vue";
import ItemSummaryReportView from "./views/ItemSummaryReportView.vue";
import ItemDetailReportView from "./views/ItemDetailReportView.vue";
import { useRouter } from "vue-router";

// import ItemSummaryPriceComponent from "./components/ItemSummaryPriceComponent.vue";
// import { http_get } from "@/src/js/http";

export default {
  components: {
    ItemList,
    ItemSummaryPriceView,
    BomPriceView,
    ItemPriceComparisonView,
    ItemSummaryReportView,
    ItemDetailReportView,
  },
  setup() {
    const debounce = (callback, delay) => {
      let tid;
      return function (...args) {
        tid && clearTimeout(tid);
        tid = setTimeout(() => {
          callback.apply(this, args);
        }, delay);
      };
    };

    const _ = window.ResizeObserver;
    window.ResizeObserver = class ResizeObserver extends _ {
      constructor(callback) {
        callback = debounce(callback, 20);
        super(callback);
      }
    };
  },
  mounted: function () {
    const router = useRouter();
    let itemId = router.currentRoute.value.query.itemId;
    console.log("itemId = " + itemId);
    if (itemId) {
      this.searchCondition = itemId;
      this.search();
    }
  },
  data() {
    return {
      isSearching: false,
      selectedIndex: 0,
      selectedUid: "",
      selectedItem: null,
      selectedItems: [],
      currentPath: window.location.hash,
      leftPanelWidth: 240,
      items: [],
      searchCondition: "",
      itemTypeSelect: "",
      isMultiSelectInParent: false,
      activeName: "hz",
      // ws: null,
      heartbeatTimer: null,
      responses: {},
      itemTypeArray: [
        {
          value: "",
          label: "全部",
        },
        {
          value: "P8_Product",
          label: "产品",
        },
        {
          value: "P8_Section",
          label: "SECTION",
        },
        {
          value: "P8_Part",
          label: "部品",
        },
        {
          value: "P8_Material",
          label: "原材料",
        },
      ],
      typeIcons: {
        P8_Part: require("@/assets/img/部件.png"),
        P8_Section: require("@/assets/img/Section.png"),
        P8_Product: require("@/assets/img/新风机.png"),
        P8_Raw_Material: require("@/assets/img/原材料.png"),
        P8_PartRevision: require("@/assets/img/部件.png"),
        P8_SectionRevision: require("@/assets/img/Section.png"),
        P8_ProductRevision: require("@/assets/img/新风机.png"),
        P8_Raw_MaterialRevision: require("@/assets/img/原材料.png"),
        Default: require("@/assets/img/part_revision_icon_16.png"),
      },
      statusIcons: {
        P8_Released: require("@/assets/img/released.png"),
        P8_Obsolete: require("@/assets/img/obsolete.png"),
      },
    };
  },
  methods: {
    test() {
      console.log(this.$refs.hz);
      this.$refs.hz.refresh();
    },
    //这个是从ItemList回调的方法
    select(item, index) {
      console.log("选择了 -> ", index, item);
      this.selectedIndex = index;
      this.selectedUid = item.item_revision_uid;
      this.selectedItem = item;
    },
    //这个也是
    selectMulti(selectedItems) {
      console.log("多选了 -> ", selectedItems);
      this.selectedItems = selectedItems;
    },
    startResize() {
      document.addEventListener("mousemove", this.resize);
      document.addEventListener("mouseup", this.stopResize);
    },
    resize(event) {
      this.leftPanelWidth = event.clientX;
    },
    stopResize() {
      document.removeEventListener("mousemove", this.resize);
      document.removeEventListener("mouseup", this.stopResize);
    },
    setMultiSelect(val) {
      console.log("setMultiSelect => " + val);
      this.isMultiSelectInParent = val;
    },
    search() {
      console.log("类型选择值为 " + this.itemTypeSelect);
      console.log("搜索条件为 " + this.searchCondition);
      // let url = "http://localhost:9021/findPartRevisions";
      let url = "/findPartRevisions";
      let t1 = this.itemTypeSelect.length > 0 ? this.itemTypeSelect : "%";
      let t2 = this.searchCondition.length > 0 ? this.searchCondition : "%";
      url = url + "?condition=" + t2 + "&itemType=" + t1;
      console.log("url = " + url);
      this.isSearching = true;
      this.$http
        .get(url)
        .then((response) => {
          // console.log(response.data);
          // console.log(this.child);
          // console.log(this.$refs);
          // this.test(response.data);
          let i = 0;
          for (const item of response.data) {
            console.log(item.item_type);
            let itemSrc = this.typeIcons[item.item_type];
            if (itemSrc == null || itemSrc == undefined) {
              itemSrc = this.typeIcons["Default"];
            }
            let statusSrc = this.statusIcons[item.statusName];
            item.icon = itemSrc;
            item.statusIcon = statusSrc;
            item.isSelected = false;
          }
          console.log(response.data);
          this.items = response.data;
          this.isSearching = false;

          //默认选择第一个
          if (this.items.length > 0) {
            this.select(this.items[0], 0);
          }
        })
        .catch((error) => {
          this.isSearching = false;
          console.log(error);
        });
    },
    onTabClick(pane, event) {
      console.log(pane, event);
      if (pane.props.name === "cbdb") {
        this.isMultiSelectInParent = true;
      } else {
        this.isMultiSelectInParent = false;
      }
    },
    // geolusSearch() {
    //   if (this.ws == null || this.ws.readyState === WebSocket.CLOSED) {
    //     this.initWebSocket(() => {
    //       this.ws.send("Hello world");
    //       this.startHeartbeat();
    //     });
    //   } else {
    //     this.ws.send("Hello world");
    //   }
    // },
    // initWebSocket(onInited) {
    //   this.ws = new WebSocket("ws://localhost:9070");
    //   this.ws.onopen = function () {
    //     console.log("WebSocket connection established.");
    //     if (onInited) {
    //       onInited();
    //     }
    //   };

    //   this.ws.onmessage = function (event) {
    //     console.log(event.data);
    //     try {
    //       const message = JSON.parse(event.data);
    //       this.handleResponse(message);
    //     } catch (e) {
    //       console.error(e);
    //     }
    //   };

    //   this.ws.onclose = function () {
    //     console.log("WebSocket connection closed.");
    //   };
    // },
    // handleResponse(response) {
    //   this.responses[response.requestId] = response;
    //   console.log("Response received for requestId: " + response.requestId);
    //   console.log("Data received:", response.datas);
    // },

    // pollResponses(requestId, onResp) {
    //   let num = 20;
    //   let intervalId = setInterval(function () {
    //     if (num-- < 0) {
    //       clearInterval(intervalId);
    //     } else if (requestId in this.responses) {
    //       clearInterval(intervalId);
    //       onResp(this.responses[requestId]);
    //     }
    //   }, 500); // 每隔0.5秒执行一次
    // },

    // sendHeartbeat() {
    //   if (this.ws.readyState === WebSocket.OPEN) {
    //     this.ws.send("PING"); // 发送心跳消息
    //   }
    // },

    // // 开始心跳
    // startHeartbeat() {
    //   this.heartbeatTimer = setInterval(() => {
    //     this.sendHeartbeat();
    //   }, 5);
    // },
  },
};
</script>

<template>
  <div class="content-page">
    <div class="input-panel">
      <div class="input-left">
        <div class="mt-4">
          <el-input
            v-model="searchCondition"
            placeholder="请输入搜索条件"
            class="input-with-select"
            @keyup.enter="search"
            style="width: 500px"
          >
            <template #prepend>
              <el-select
                v-model="itemTypeSelect"
                placeholder="选择类型"
                style="width: 115px"
              >
                <el-option
                  v-for="item in itemTypeArray"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
            <template #append>
              <el-button @click="search">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </div>
      </div>
      <!-- <div class="input-right">
        <el-button type="primary" @click="geolusSearch">形状检索</el-button>
      </div> -->
    </div>
    <div class="mainPanel">
      <div :style="{ width: leftPanelWidth + 'px' }">
        <ItemList
          :items="items"
          :isMultiSelectInParent="isMultiSelectInParent"
          v-loading="isSearching"
          @select="select"
          @selectMulti="selectMulti"
        ></ItemList>
        <!-- @select是从子项里传回来的方法 -->
      </div>
      <div class="resizer" @mousedown="startResize"></div>
      <div class="right-panel">
        <el-tabs
          v-model="activeName"
          type="border-card"
          @tab-click="onTabClick"
        >
          <el-tab-pane label="汇总" name="hz">
            <ItemSummaryPriceView
              :uid="selectedUid"
              :item="selectedItem"
              :items="selectedItems"
              :activeName="activeName"
              paneName="hz"
              @setMultiSelect="setMultiSelect"
              ref="hz"
            ></ItemSummaryPriceView>
          </el-tab-pane>
          <el-tab-pane label="结构" name="jg"
            ><BomPriceView
              :uid="selectedUid"
              :item="selectedItem"
              :items="selectedItems"
              :activeName="activeName"
              paneName="jg"
              @setMultiSelect="setMultiSelect"
            ></BomPriceView
          ></el-tab-pane>
          <el-tab-pane label="成本对比" name="cbdb"
            ><ItemPriceComparisonView
              :uid="selectedUid"
              :item="selectedItem"
              :items="selectedItems"
              :activeName="activeName"
              paneName="cbdb"
              @setMultiSelect="setMultiSelect"
            ></ItemPriceComparisonView
          ></el-tab-pane>
          <el-tab-pane label="汇总统计" name="hztj"
            ><ItemSummaryReportView
              :uid="selectedUid"
              :item="selectedItem"
              :items="selectedItems"
              :activeName="activeName"
              paneName="hztj"
              @setMultiSelect="setMultiSelect"
            ></ItemSummaryReportView
          ></el-tab-pane>
          <el-tab-pane label="明细统计" name="mstj"
            ><ItemDetailReportView
              :uid="selectedUid"
              :item="selectedItem"
              :items="selectedItems"
              :activeName="activeName"
              paneName="mstj"
              @setMultiSelect="setMultiSelect"
            ></ItemDetailReportView
          ></el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<style>
nav {
  padding: 5px;
}

nav a {
  font-weight: bold;
  color: #2c3e50;
}

nav a.router-link-exact-active {
  color: #42b983;
}

.content-page {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: auto;
}
.mainPanel {
  display: flex;
  /* height: 80vh; */
  height: auto;
}
.input-panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  margin-bottom: 10px;
  height: 40px;
}

.dropdown {
  margin-right: 10px;
  height: 25px;
}

.search-input {
  height: 19px;
  width: 300px;
}
.button {
  margin-left: 10px;
  height: 30px;
  width: 140px;
  background-color: #11b0f4;
  border-radius: 5px;
}
.resizer {
  top: 0;
  right: 0;
  width: 4px;
  /* height: 90vh;  */
  bottom: 0;
  background-color: #ccc;
  cursor: col-resize;
  flex-shrink: 0;
}
.right-panel {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  /*占满剩余空间 */
  flex: 1;
}

.bottom-href-panel {
  display: flex;
  /* flex-direction: row; */
  justify-content: start;
  align-items: flex-end;
  height: 100%;
  gap: 5px;
  padding-left: 10px;
}

.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}
</style>
